<template>
  <div style="padding:20px">
    <el-card class="kb-card" shadow="never">
      <div style="display: flex;justify-content: space-between;align-items: center;">
        <h2>知识库管理</h2>
        <el-button type="primary" @click="dialogVisible = true">
          
          <el-icon><Plus/></el-icon>
          创建知识库</el-button>
      </div>
      <el-dialog title="知识库信息" v-model="dialogVisible">
        <el-form :model="form">
          <el-form-item label="名称">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="简介">
            <el-input type="textarea" v-model="form.description"></el-input>
          </el-form-item>
          <el-form-item label="模型">
            <el-select v-model="form.model" placeholder="请选择模型">
              <el-option label="含光" value="含光"></el-option>
              <!-- Add more models as needed -->
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createKnowledgeBase">确定</el-button>
        </span>
      </el-dialog>
      <div v-if="knowledgeBases.length === 0" style="text-align: center; margin-top: 50px;">
        <i class="el-icon-document-empty" style="font-size: 50px;"></i>
        <!-- <p></p> -->
        <el-empty description="暂无知识库"></el-empty>
      </div>
      <el-row :gutter="20" v-else>
        <el-col :span="6" v-for="kb in knowledgeBases" :key="kb.id">
          <el-card shadow="hover" @click="viewKnowledgeBase(kb.id)">
            <h3>{{ kb.name }}</h3>
            <p>
              <el-alert :title="kb.description" type="info" :closable="false" />
            </p>
            <p><strong>向量化模型:</strong> {{ kb.model }}</p>
            <div style="width: 100%;">
              <el-row :gutter="12">
                <el-col :span="12">
                  <el-button type="primary" size="small" style="width: 100%;" @click.stop="editKnowledgeBase(kb)">
                    <el-icon>
                      <Edit />
                    </el-icon>
                    编辑</el-button>
                </el-col>
                <el-col :span="12"> <el-button type="danger" size="small" style="width: 100%;"
                    @click.stop="deleteKnowledgeBase(kb.id)">
                    <el-icon>
                      <Delete />
                    </el-icon>删除</el-button>
                </el-col>
              </el-row>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus';

export default {
  data() {
    return {
      dialogVisible: false,
      form: {
        name: '',
        description: '',
        model: '含光'
      },
      knowledgeBases: [],
      editingKB: null
    };
  },
  methods: {
    async fetchKnowledgeBases() {
      try {
        const response = await fetch(`${import.meta.env.VITE_API_URL}/knowledgeBases`, {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`
          }
        });
        if (response.status === 401) {
          localStorage.removeItem('access_token');
          this.$router.push('/login');
          return;
        }
        let data = await response.json();
        data = data.data
        this.knowledgeBases = data;
      } catch (error) {
        console.error(error);
      }
    },
    async createKnowledgeBase() {
      try {
        const response = await fetch(`${import.meta.env.VITE_API_URL}/knowledgeBases`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`
          },
          body: JSON.stringify(this.form)
        });
        if (response.status === 401) {
          localStorage.removeItem('access_token');
          this.$router.push('/login');
          return;
        }
        const data = await response.json();
        if (response.ok) {
          ElMessage.success(data.msg);
          this.dialogVisible = false;
          this.fetchKnowledgeBases(); // Refresh knowledge bases list
        } else {
          ElMessage.error(data.msg);
        }
      } catch (error) {
        console.error(error);
      }
    },
    editKnowledgeBase(kb) {
      this.editingKB = kb;
      this.form = { ...kb };
      this.dialogVisible = true;
    },
    async updateKnowledgeBase() {
      try {
        const response = await fetch(`${import.meta.env.VITE_API_URL}/knowledgeBases/${this.form.id}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`
          },
          body: JSON.stringify(this.form)
        });
        if (response.status === 401) {
          localStorage.removeItem('access_token');
          this.$router.push('/login');
          return;
        }
        const data = await response.json();
        if (response.ok) {
          ElMessage.success(data.msg);
          this.dialogVisible = false;
          this.fetchKnowledgeBases(); // Refresh knowledge bases list
        } else {
          ElMessage.error(data.msg);
        }
      } catch (error) {
        console.error(error);
      }
    },
    async deleteKnowledgeBase(id) {
      try {
        const response = await fetch(`${import.meta.env.VITE_API_URL}/knowledgeBases/${id}`, {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`
          }
        });
        if (response.status === 401) {
          localStorage.removeItem('access_token');
          this.$router.push('/login');
          return;
        }
        const data = await response.json();
        if (response.ok) {
          ElMessage.success(data.msg);
          this.fetchKnowledgeBases(); // Refresh knowledge bases list
        } else {
          ElMessage.error(data.msg);
        }
      } catch (error) {
        console.error(error);
      }
    },
    viewKnowledgeBase(id) {
      this.$router.push(`/knowledge-base/${id}`);
    }
  },
  watch: {
    dialogVisible(visible) {
      if (!visible && this.editingKB) {
        this.form = {
          name: '',
          description: '',
          model: '含光'
        };
        this.editingKB = null;
      }
    }
  },
  mounted() {
    this.fetchKnowledgeBases();
  }
};
</script>

<style scoped>
.kb-card {
  width: 100%;
  text-align: left;
  min-height: 600px;
}

.el-row {
  margin-top: 20px;
}

.el-card {
  margin-bottom: 20px;
  cursor: pointer;
}

</style>